1
Easy2Siksha
GNDU Question Paper-2021
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: Two Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any
Four questions.
1. (a) What do you understand by Number System ? Convert (725.55) into Binary, Octal
and Hexadecimal Number Systems.
(b) Explain the concept of Pseudo Code by taking suitable example.
2. (a) Explain various data types supported by C Programming Language giving suitable
examples.
(b) How Constant is different from Variable ? Explain the use of String Constants using
suitable example.
3. Explain the use of the following operators using suitable examples:
(a) Arithmetic Operators
(b) Unary Operators.
4. (a) Explain the use of gets() and puts() using suitable example.
(b) What is the purpose of the printf() function? How is it used within C program?
Compare it with the putchar function.
5. (a) Discuss the use of different forms of If-else statement using suitable example.
(b) What is the purpose of Continue statement ? Explain its use. Compare it with break
statement.
2
Easy2Siksha
6. What is Function? What are differences between passing an array to a function and
passing a single-valued data item to a function? Explain using example.
7. (a) Explain the use of pointers in Call by Less Reference parameter passing for functions
using example.
(b) Write a program using pointers to swap the values of two integer numbers.
8. (a) What is Structure? How it is different from an array? How can a structure member
be accessed? Explain using suitable example.
(b) Explain the concept of Union. In what way does the initialization of a union variable
differ from the initialization of a structure variable?
3
Easy2Siksha
GNDU Answer Paper-2021
B.A 2
nd
Semester
COMPUTER SCIENCE
(Programming Using C)
Time Allowed: Two Hours Maximum Marks: 75
Note: There are Eight questions of equal marks. Candidates are required to attempt any
Four questions.
1. (a) What do you understand by Number System ? Convert (725.55) into Binary, Octal
and Hexadecimal Number Systems.
(b) Explain the concept of Pseudo Code by taking suitable example.
Ans: Understanding Number Systems as a Fun Story
Imagine you're part of a secret club, and this club has four secret codes to write numbers.
Each code is a different "language" to express numbers, and you’re about to become a pro
at decoding and translating these! The four most important languages in our secret club are:
1. Decimal System (Base 10): This is our everyday language where we use 10 symbols
(0-9). It’s like speaking your native tongue—easy and natural.
2. Binary System (Base 2): Computers speak this language! It uses only two symbols: 0
and 1. Think of it as "Computer Morse Code."
3. Octal System (Base 8): Here, you have eight symbols (0-7). It’s like a compact way of
writing binary numbers.
4. Hexadecimal System (Base 16): This one is fancy and uses 16 symbols (0-9 and A-F).
It’s super cool because it's shorthand for long binary numbers.
Now, let’s dive into the adventure of converting a number 725.55725.55725.55 from
decimal (our default language) into Binary, Octal, and Hexadecimallike translating a story
into three different languages!
The Decimal Number: 725.55
We begin with a number in decimal form. Our goal is to express it in other number
systems. To do this, we’ll break the number into two parts:
1. The whole number part: 725
4
Easy2Siksha
2. The fractional part: 0.550.550.55
We’ll convert each part separately.
1. Converting Decimal to Binary (Base 2)
Step 1: Convert the whole number 725 to Binary
To convert a decimal whole number to binary:
Keep dividing the number by 2, noting the remainders as you go.
Stop when the quotient is 0.
Write the remainders in reverse order to get the binary number.
Conversion:
1. 725÷2=362, remainder = 111
2. 362÷2=181, remainder = 000
3. 181÷2=901, remainder = 111
4. 90÷2=45, remainder = 000
5. 45÷2=22, remainder = 111
6. 22÷2=11, remainder = 000
7. 11÷2=5, remainder = 111
8. 5÷2=2, remainder = 111
9. 2÷2=12 , remainder = 000
10. 1÷2=01 , remainder = 111
Binary of 725: 1011010101
Step 2: Convert the fractional part 0.55 to Binary
For fractions, multiply the fraction by 2 and note the integer part. Continue with the
fractional part until you get 0 or reach a satisfactory precision.
Conversion:
1. 0.55×2=1.10, integer = 1
2. 0.10×2=0.20, integer = 0
3. 0.20×2=0.40, integer = 0
4. 0.40×2=0.80, integer = 0
5. 0.80×2=1.60, integer = 1
6. 0.60×2=1.20, integer = 1
5
Easy2Siksha
7. 0.20×2=0.40, integer = 000 (Repeats)
Binary of 0.55: 0.100011...
Final Binary: 1011010101.100011...
2. Converting Decimal to Octal (Base 8)
Step 1: Convert the whole number 725 to Octal
For octal, divide the whole number by 8 instead of 2.
Conversion:
1. 725÷8=90, remainder = 555
2. 90÷8=11, remainder = 222
3. 11÷8=1, remainder = 333
4. 1÷8=0 , remainder = 111
Octal of 725: 1325
Step 2: Convert the fractional part 0.550.550.55 to Octal
For fractions, multiply by 8 and note the integer part.
Conversion:
1. 0.55×8=4.40, integer = 4
2. 0.40×8=3.20, integer = 3
3. 0.20×8=1.60, integer = 1
4. 0.60×8=4.80, integer = 4
5. 0.80×8=6.40, integer = 6
Octal of 0.55: 0.43146...
Final Octal: 1325.43146...
3. Converting Decimal to Hexadecimal (Base 16)
Step 1: Convert the whole number 725725725 to Hexadecimal
For hexadecimal, divide by 16.
Conversion:
1. 725÷16=45, remainder = 5
2. 45÷16=2, remainder = 131313 (Represented as DDD in Hex)
3. 2÷16=0, remainder = 2
6
Easy2Siksha
Hexadecimal of 725: 2D5
Step 2: Convert the fractional part 0.550.550.55 to Hexadecimal
For fractions, multiply by 16 and note the integer part.
Conversion:
1. 0.55×16=8.80, integer = 8
2. 0.80×16=12.80, integer = 121212 (Represented as CCC in Hex)
3. 0.80×16=12.80 (Repeats)
Hexadecimal of 0.55: 0.8C...
Final Hexadecimal: 2D5.8C...
Final Translations of 725.55
1. Binary: 1011010101.
2. Octal: 1325.43146.
3. Hexadecimal: 2D5.8C..
Key Takeaways (Memory Trick)
Think of these number systems as languages of numbers:
Binary is the computer’s heartbeat (0s and 1s).
Octal is a shortened Binary (groups of 3).
Hexadecimal is computer slang (groups of 4).
Always divide the whole part and multiply the fractional part to switch between languages.
With practice, you'll become fluent in all four number systems!
(b) What is Pseudo Code?
Pseudo code is like writing a recipe for your computer before you cook (write the actual
program in C or any other language). It’s not written in a real programming language like C,
Python, or Java, but it’s written in plain, simple English that explains the steps of solving a
problem. It’s a blueprint that helps you plan your program before actually coding it.
Why Do We Use Pseudo Code?
Clarity: It helps you focus on the logic of the program rather than worrying about
syntax (the rules of programming languages like C).
Problem Solving: You can think through the solution step-by-step.
7
Easy2Siksha
Teamwork: It’s easy to explain your ideas to others using pseudo code because it’s
written in a language everyone understands.
Think of pseudo code as a bridge between your brain (where ideas form) and the computer
(which needs code to run).
A Fun Analogy: Cooking Pasta
Let’s say you want to make pasta. You’re not writing a cookbook yet, just jotting down steps
in your notebook for practice. Here’s how your pseudo code might look:
1. Boil water.
2. Add pasta to boiling water.
3. Cook pasta for 10 minutes.
4. Drain water.
5. Add sauce and mix.
6. Serve.
Notice how these steps aren’t written in a specific language but are clear enough to follow?
That’s pseudo code!
Example: Pseudo Code for a Real Program
Now let’s connect it to programming. Imagine you’re building a program that calculates the
sum of two numbers. Here’s how the pseudo code might look:
1. Start.
2. Take input for the first number and store it as num1.
3. Take input for the second number and store it as num2.
4. Add num1 and num2, and store the result as sum.
5. Display the value of sum.
6. Stop.
When you write this in C, it would look like this:
8
Easy2Siksha
Steps to Write Good Pseudo Code (Just Like Writing a Great Recipe)
1. Start Simple: Write in plain language that’s easy to understand.
2. Be Organized: Write steps in the correct sequence, just like in a recipe.
3. Use Keywords Sparingly: Words like "Start," "Stop," "If," "Then," "Else" are common
in pseudo code.
4. Don’t Worry About Syntax: Forget about semicolons ; or curly braces {}—you’ll deal
with that when you write the actual code.
5. Focus on the Logic: The purpose is to describe the steps needed to solve the
problem, not to teach the computer yet.
Example 2: A Fun Real-World Problem
Problem: You’re designing a program to tell if a number is odd or even.
Here’s the pseudo code:
1. Start.
2. Take input for a number and store it as num.
3. Divide num by 2.
4. If the remainder is 0, display "The number is even."
5. Otherwise, display "The number is odd."
6. Stop.
C Code Translation:
The Importance of Pseudo Code
Saves Time: Planning your program in pseudo code helps you write better code
faster because you already know the steps.
Avoids Errors: Thinking through the logic first reduces mistakes when coding.
9
Easy2Siksha
Teaches Logical Thinking: For beginners, pseudo code is a great way to focus on
problem-solving instead of getting stuck with syntax.
A Fun Twist: Pseudo Code for Morning Routine
Imagine you want to create a "program" for your morning routine. Here’s the pseudo
code:
1. Start.
2. Wake up.
3. Brush teeth.
4. Take a shower.
5. Get dressed.
6. Eat breakfast.
7. Leave for work.
8. Stop.
Now, if you wanted, you could turn this into a real C program (though your computer might
not find it very useful!).
Practice Makes Perfect!
Here’s a challenge for you: Try writing pseudo code for these simple problems:
1. Find the largest of three numbers.
2. Check if a number is positive, negative, or zero.
3. Calculate the factorial of a number.
Conclusion
Pseudo code is your secret weapon to think like a programmer without worrying about
syntax. It’s the storyboarding stage of your program, where you outline your ideas clearly
before diving into code. Just like you wouldn’t start cooking without planning your recipe,
you shouldn’t start coding without writing pseudo code.
10
Easy2Siksha
2. (a) Explain various data types supported by C Programming Language giving suitable
examples.
(b) How Constant is different from Variable ? Explain the use of String Constants using
suitable example.
Ans: A Fun Story to Understand Data Types in C Programming
Imagine you're a magician who just found a treasure chest full of magical tools! Each tool
can store a specific type of treasure. But here's the catch: you need to know what each tool
is meant to store, or the magic won't work. These tools represent data types in the magical
land of C programming!
The Magic Tools (Data Types in C)
C provides a variety of data types to store different kinds of treasures (values). Here’s the
full list of the magical tools:
1. Integer (int) The Whole Number Sack
Imagine a sack that can hold whole numbers, like coins or stones. It doesn't allow fractions
or decimalsjust pure, complete items.
Range: Typically from -32,768 to 32,767 for a 16-bit system.
Examples:
o int age = 25; // Stores a person's age
o int numberOfApples = 100; // Stores how many apples you have
2. Float (float) The Potion Bottle
This is a glass bottle for liquid treasures—fractions, decimals, or measurements. It’s perfect
for storing potion quantities like 3.14 liters or 7.25 liters.
Size: 4 bytes
Examples:
o float pi = 3.14; // Stores the value of π
o float distance = 5.67; // Stores a distance in kilometers
3. Double (double) The Bigger Potion Bottle
When a regular potion bottle isn’t enough, you grab this one! It holds more precise and
larger decimal values.
Size: 8 bytes
Examples:
o double distanceToSun = 149600000.123456; // Very large and precise
number
11
Easy2Siksha
o double scientificValue = 0.000002345; // Stores small precise measurements
4. Character (char) The Single Rune Scroll
This tiny scroll can store a single rune or character. It’s perfect for initials, symbols, or a
single letter.
Size: 1 byte
Examples:
o char grade = 'A'; // Stores a grade in school
o char symbol = '#'; // Stores a special character
5. Void (void) The Empty Box
What if you need a tool that doesn’t store anything? That’s the void type! It’s used for
functions that don’t return a treasure.
Examples:
o A magician’s spell that doesn’t need to give back anything, like void
castSpell() { ... }
6. Boolean (_Bool) The Magic Light
This tool is like a magic lamp: it can only be on (true) or off (false). It helps you decide things
like "Is the door open?"
Size: 1 byte
Examples:
o _Bool isDoorOpen = 1; // True means the door is open
o _Bool isLampOn = 0; // False means the lamp is off
Modifiers: Adding Flavors to Your Tools
Sometimes, you want to customize your tools for specific tasks. That’s where data type
modifiers come in:
1. Signed and Unsigned
Signed: The default. It allows both positive and negative values.
Unsigned: Only allows positive values but can store a larger range.
12
Easy2Siksha
Example:
2. Short and Long
Short: A smaller version of the tool, for small numbers.
Long: A bigger version, for larger numbers.
Example:
short int smallNumber = 32000; // Smaller range
long int largeNumber = 123456789; // Larger range
How to Pick the Right Tool?
When you're in the magical world of programming, choosing the right tool is important.
Here’s a cheat sheet to help you:
1. Whole numbers: Use int or unsigned int.
2. Decimal numbers: Use float or double.
3. Single characters: Use char.
4. Yes/No decisions: Use _Bool.
5. No return values: Use void.
A Magical Spell (Code Example)
Let’s use all the magical tools in a simple program:
#include <stdio.h>
int main() {
int age = 25; // Whole number
float pi = 3.14; // Decimal number
double bigNumber = 1.23456789; // Large decimal number
char initial = 'A'; // Single character
_Bool isStudent = 1; // Boolean value (true/false)
printf("Age: %d\n", age);
printf("Value of pi: %.2f\n", pi);
13
Easy2Siksha
printf("Big number: %.8f\n", bigNumber);
printf("Initial: %c\n", initial);
printf("Is student? %d\n", isStudent);
return 0;
}
Output:
yaml
Age: 25
Value of pi: 3.14
Big number: 1.23456789
Initial: A
Is student? 1
Fun Mnemonic to Remember the Types
Here’s a short rhyme to help you remember:
“Integers are whole, Floats like to roll,
Doubles go deep, Characters keep,
Booleans decide, Void’s empty inside!”
Conclusion
C programming is like a magical adventure, and data types are your tools for storing
treasures of different kinds. By understanding these types, you can write powerful spells
(programs) and solve problems easily.
(b) The Story of Constants and Variables: A Simple Tale
Ans: Imagine you have a magical notebook where you can write down numbers, words, or
anything you want. This notebook has two types of boxes: Constants and Variables. These
two boxes work differently, and understanding them is key to learning programming.
Constants: The Unchanging Guardians
Constants are like super-strict guardians. Once you write something in their box, you cannot
change it. They are stubborn but reliable, ensuring that the value they hold stays the same
throughout the story (or program). For example, if you tell a constant:
14
Easy2Siksha
"Your value is 5, and it will never change,"
it will stick to that promise forever.
Variables: The Flexible Helpers
Variables, on the other hand, are like friendly assistants. You can tell them,
"Today, your value is 10,"
and later say,
"Actually, change it to 20,"
and they’ll happily oblige. They are flexible and can store different values during your
program.
How Constants and Variables Work in Programming
In programming, constants and variables are used to store data. The main difference is that
constants don’t change once defined, while variables can be updated during the program’s
execution. Let’s look at an example in C programming:
Example 1: Constants
#include <stdio.h>
int main() {
const int MAX_AGE = 100; // Declaring a constant
printf("The maximum age is: %d\n", MAX_AGE);
// MAX_AGE = 110; // This will give an error because MAX_AGE is a constant
return 0;
}
Here, MAX_AGE is a constant. It’s declared using the const keyword, and its value (100)
cannot be changed.
Example 2: Variables
#include <stdio.h>
int main() {
int age = 20; // Declaring a variable
printf("Initial age: %d\n", age);
age = 25; // Updating the variable's value
printf("Updated age: %d\n", age);
15
Easy2Siksha
return 0;
}
In this case, age is a variable. You can change its value from 20 to 25 without any issues.
Introducing String Constants: The Wordkeepers
Now let’s talk about string constants, which are a special type of constant. Strings are
collections of characters, like words or sentences. For example:
"Hello"
"Programming is fun!"
In C, string constants are written inside double quotes ("). These are like unchanging magical
words. You cannot modify a string constant after declaring it.
Why Use String Constants?
String constants are super handy for things like:
1. Printing Messages: Displaying information to the user.
2. Labels or Titles: Assigning unchanging names.
3. Fixed Data: Storing something permanent, like "Name: ", "Error: File not found".
Example of String Constants
#include <stdio.h>
int main() {
const char *greeting = "Hello, World!"; // String constant
printf("%s\n", greeting); // Prints: Hello, World!
// greeting[0] = 'h'; // This will give an error because it’s a constant
return 0;
}
In this example:
The string "Hello, World!" is stored in the constant greeting.
Trying to change it (e.g., greeting[0] = 'h';) will cause an error because constants
cannot be modified.
The Fun Analogy: Constants vs. Variables
16
Easy2Siksha
Imagine a bakery. The bakery has:
1. Constants: The store's name on the signboard ("Delicious Bakes"). It never changes,
no matter what.
2. Variables: The price of bread (Price = 50). This might change daily depending on
demand or supply.
So, in the bakery:
The signboard is like a constant fixed and permanent.
The price tag is like a variable flexible and changeable.
Why Are Constants and Variables Important?
Constants
Ensure reliability (no accidental changes).
Useful for values like mathematical constants (PI = 3.14).
Variables
Allow flexibility (store changing data).
Used for user inputs, calculations, or any data that can vary.
More on Strings in C
Strings in C are stored as arrays of characters. For example:
char name[] = "Alice";
This creates an array that looks like this in memory: | A | l | i | c | e | \0 | The special
character \0 marks the end of the string.
String Manipulation
C provides functions to work with strings:
strlen(): Find the length of a string.
strcpy(): Copy one string into another.
strcmp(): Compare two strings.
Here’s an example:
#include <stdio.h>
#include <string.h>
int main() {
17
Easy2Siksha
char name1[] = "Alice";
char name2[] = "Bob";
// Comparing strings
if (strcmp(name1, name2) == 0) {
printf("The names are the same.\n");
} else {
printf("The names are different.\n");
}
return 0;
}
Conclusion: Constants vs. Variables and Strings
To sum up:
1. Constants: Unchanging, reliable, and declared with const.
2. Variables: Flexible, changeable, and declared normally.
3. String Constants: Useful for storing fixed text, declared inside double quotes (").
By thinking of constants as the strict guardians and variables as the friendly helpers, you’ll
never forget how they work. And remember: strings are just words stored in magical boxes
to make your programs more meaningful and interactive!
3. Explain the use of the following operators using suitable examples:
(a) Arithmetic Operators
(b) Unary Operators.
Ans: In C-land, whenever people needed to solve problems with numbers, they called on
the Arithmetic Wizards. These wizards could add, subtract, multiply, divide, and even find
remainders! But then came the mysterious Unary Wizards, who could magically change the
sign of a number or even increase or decrease it with just a wave of their wand.
18
Easy2Siksha
Let’s dive deeper into their powers and how they work.
Arithmetic Wizards (Arithmetic Operators) 󼘆󼘇󼙂󼛌󼛍󼛎󼙄󼙅󼛏󼙆󼙇󼙈󼘐󼛐󼘑󼛑󼘒󼛒󼛓󼛔󼘓󼘗󼘘󼘜󼛕󼘙󼘚󼘛
The Arithmetic Wizards are responsible for performing basic math operations. They work
with two numbers at a time (called operands). Think of them like chefs who mix two
ingredients to create a dish. Here are their powers:
1. Addition (+)
Wizard Addus takes two numbers and combines them.
Example:
int a = 5, b = 3;
int result = a + b; // result = 8
Story Connection: Addus loves pairing apples. If you give him 5 apples and 3 apples, he’ll
give you a basket with 8 apples.
2. Subtraction (-)
Wizard Subby removes one number from another.
Example:
int a = 5, b = 3;
int result = a - b; // result = 2
Story Connection: Subby loves taking apples away. If you have 5 apples and he takes away
3, you’re left with 2.
3. Multiplication (*)
Wizard Multiplus multiplies two numbers together.
Example:
int a = 5, b = 3;
int result = a * b; // result = 15
Story Connection: Multiplus grows apple trees. If each tree grows 5 apples and you have 3
trees, you’ll get 15 apples.
4. Division (/)
Wizard Divider splits one number by another.
Example:
int a = 6, b = 3;
int result = a / b; // result = 2
Story Connection: Divider loves sharing apples equally. If you have 6 apples and 3 friends,
each gets 2 apples.
19
Easy2Siksha
Note: Be careful! Divider doesn’t like dividing by 0. If you try, he gets angry and causes an
error. 󺠣󺠤󺠥󺠦󺠧󺠨
5. Modulus (%)
Wizard Moddy finds the remainder after dividing one number by another.
Example:
int a = 7, b = 3;
int result = a % b; // result = 1
Story Connection: Moddy is obsessed with leftovers. If you try to share 7 apples among 3
friends, 1 apple will always be left over.
Unary Wizards (Unary Operators) 󼘆󼘇󼘈󼛂󼘊󼘋󼘭󼛃󼛄󼘮󼘯󼛅󼘰󼛆󼛇󼛈󼛉󼘱󼘲󼛊󼘳󼘴󼘵󼘶󼘷󼘸󼘗󼘘󼛋󼘙󼘜
Unlike the Arithmetic Wizards, Unary Wizards only work with one number at a time. They’re
quick and efficient, like solo performers. Here are their magical powers:
1. Positive (+)
Wizard Positive is simple. She just ensures that the number stays positive.
Example:
int a = +5; // a = 5
Story Connection: Positive Wizard just smiles and says, “Keep it positive!”
2. Negative (-)
Wizard Negative flips the sign of the number.
Example:
int a = 5;
int b = -a; // b = -5
Story Connection: Negative Wizard turns things upside down. If you have 5 apples, she’ll
magically turn them into -5 apples (debt).
3. Increment (++)
Wizard Increasy adds 1 to a number every time you call her.
Example:
int a = 5;
a++; // a = 6
Story Connection: Increasy is like a gardener. She adds one apple to your basket every time
you visit her.
20
Easy2Siksha
Fun Fact:
Increasy can work in two ways:
o Post-Increment (a++): First uses the number, then increments it.
Example:
int a = 5;
int b = a++; // b = 5, a = 6
o Pre-Increment (++a): Increments the number first, then uses it.
Example:
int a = 5;
int b = ++a; // b = 6, a = 6
4. Decrement (--)
Wizard Decreasy subtracts 1 from a number.
Example:
int a = 5;
a--; // a = 4
Story Connection: Decreasy is like a borrower. She takes away one apple each time you visit
her.
Fun Fact:
Like her sister Increasy, Decreasy also works in two ways:
o Post-Decrement (a--): First uses the number, then decrements it.
Example:
int a = 5;
int b = a--; // b = 5, a = 4
o Pre-Decrement (--a): Decrements the number first, then uses it.
Example:
int a = 5;
int b = --a; // b = 4, a = 4
A Fun Journey Together 󷓠󷓡󷓢󷓣󷓤󷓥󷓨󷓩󷓪󷓫󷓦󷓧󷓬
Now that we’ve met the Arithmetic and Unary Wizards, let’s see how they can work
together in a program.
21
Easy2Siksha
Example Code:
#include <stdio.h>
int main() {
int x = 10, y = 3;
// Arithmetic Wizards in Action
printf("Addition: %d\n", x + y); // 13
printf("Subtraction: %d\n", x - y); // 7
printf("Multiplication: %d\n", x * y); // 30
printf("Division: %d\n", x / y); // 3
printf("Modulus: %d\n", x % y); // 1
// Unary Wizards in Action
printf("Positive: %d\n", +x); // 10
printf("Negative: %d\n", -x); // -10
printf("Increment (Post): %d\n", x++); // 10, then x becomes 11
printf("Increment (Pre): %d\n", ++x); // 12
printf("Decrement (Post): %d\n", x--); // 12, then x becomes 11
printf("Decrement (Pre): %d\n", --x); // 10
return 0;
}
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
22
Easy2Siksha
Positive: 10
Negative: -10
Increment (Post): 10
Increment (Pre): 12
Decrement (Post): 12
Decrement (Pre): 10
Wrapping Up the Tale
The Arithmetic and Unary Wizards work tirelessly in the land of C Programming to solve
problems and make calculations easier. By understanding their magical abilities, you can
create programs that handle math operations with ease.
Remember:
Arithmetic Wizards always work with two numbers.
Unary Wizards are solo performers, working with just one number.
4. (a) Explain the use of gets() and puts() using suitable example.
(b) What is the purpose of the printf() function? How is it used within C program?
Compare it with the putchar function.
Ans; Once upon a time, in the magical land of C Programming, there were two good friends,
gets() and puts(), who lived in the Input and Output Village. They had one important job:
helping programmers interact with their computer by reading and displaying text.
One day, a young programmer came to the Input and Output Village and asked, “Can you
help me make a program that takes a sentence from the user and shows it back to them?
But please explain it simply, so I can remember forever!”
The two friends, gets() and puts(), smiled and said, “Sure! That’s what we’re here for!”
Meet gets(): The Listener 󹴮󹴯󹴰󹴱󹴲󹴳
gets() is like a kind and patient listener. Its job is to take a complete line of text (a string)
from the user. It doesn’t stop at the first word or the first spaceit listens to the whole
sentence until the user presses the Enter key.
Imagine you're writing a letter, and gets() is your assistant. You dictate the entire line, and it
writes it down neatly, just as you say it.
23
Easy2Siksha
How gets() Works:
1. It takes input from the user.
2. It stores the input in a string variable.
3. It stops only when the Enter key is pressed.
Example of gets():
#include <stdio.h>
int main() {
char name[50]; // A place to store the input (string).
printf("Enter your name: ");
gets(name); // Takes the entire input, even if it contains spaces.
printf("Nice to meet you, ");
puts(name); // Displays what was entered.
return 0;
}
Output of the Program:
Enter your name: Harry Potter
Nice to meet you, Harry Potter
Here’s what happened:
1. The programmer used gets(name) to take the entire sentence "Harry Potter".
2. gets() didn't stop at "Harry" or the space. It took the whole name until the Enter key.
3. Later, the program used puts() (more about it below!) to display the name back to
the user.
Meet puts(): The Storyteller 󹵪󹵧󹵨󹵩
puts() is like a cheerful storyteller. Its job is to print a string for the user to see. It takes a
string and shows it on the screen, always adding a neat new line at the end.
24
Easy2Siksha
Think of puts() as your friend who loves to announce things loudly and clearly. Once you
give it something to say, it says it, loud and proud, followed by a little pause (a new line).
How puts() Works:
1. It takes a string as input.
2. It displays the string on the screen.
3. It automatically moves to the next line after displaying.
Example of puts():
#include <stdio.h>
int main() {
char message[] = "Welcome to C Programming!";
puts(message); // Prints the message with a new line.
return 0;
}
Output of the Program:
Welcome to C Programming!
Notice how puts() automatically added a new line after displaying the message.
The gets() and puts() Duo in Action 󷗛󷗜
Let’s create a fun little program where both gets() and puts() work together to make things
happen!
Example: A Friendly Chatbot
#include <stdio.h>
int main() {
char userName[50];
char favoriteFood[50];
// Asking for the user's name
25
Easy2Siksha
printf("What's your name? ");
gets(userName);
// Greeting the user
printf("Hello, ");
puts(userName);
// Asking for the user's favorite food
printf("What’s your favorite food? ");
gets(favoriteFood);
// Repeating their favorite food back to them
printf("Yum! I love ");
puts(favoriteFood);
return 0;
}
Output of the Program:
What's your name? Alice Wonderland
Hello, Alice Wonderland
What’s your favorite food? Pizza
Yum! I love Pizza
The Problems with gets() 󺪸󺪹
As wonderful as gets() seems, it has a big problem: it doesn’t care how much space is
available in the string variable. If the user enters more characters than the variable can hold,
it can cause errors or unexpected behavior.
For Example:
char smallArray[5];
gets(smallArray); // User enters "Harry Potter", but the array is too small to hold it.
26
Easy2Siksha
This can lead to a buffer overflow (a type of bug), which makes the program crash or behave
unpredictably.
The Safer Alternative: fgets()
To fix this issue, C programmers now use fgets() instead of gets(). It allows you to specify
how many characters to read, making it safer.
Syntax of fgets():
fgets(variable, size, stdin);
Example: Using fgets()
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Takes input but limits it to the size of the array.
printf("Hello, ");
puts(name);
return 0;
}
Output of the Program:
Enter your name: Hermione Granger
Hello, Hermione Granger
Summary: Remembering gets() and puts() as Friends 󷇴󷇵󷇶󷇷󷇸󷇹
Here’s a simple way to remember the duo:
gets() is the polite listener who takes input from the user.
puts() is the cheerful announcer who prints text with a smile (a new line).
27
Easy2Siksha
Although gets() is a little outdated, knowing how it works helps you understand the history
of C programming. Always use fgets() for safety, but remember the spirit of gets() and its fun
partnership with puts().
(b) Answer: What is printf() and How Does it Work?
The printf() function in the C programming language is a powerful tool for sending messages
from your program to the screen. It’s like giving your ship a megaphone to share important
updates, such as:
Numbers
Words
Sentences
Even special calculations!
How printf() Works
Think of printf() as your way of telling the ship exactly what to say and how to say it. For
example, you could tell it:
“Hey, print this number: 42!”
“Announce my name is Captain Code!”
Here’s how you use it in a program:
#include <stdio.h> // Include the library for input/output
int main() {
int age = 20; // Define a variable
printf("Hello, I am %d years old!\n", age); // Use printf to display text and the value of age
return 0;
}
Breaking It Down
Hello, I am %d years old!\n: This is the format string, telling printf() what to print.
The %d is a placeholder for a number (an integer), and \n moves the cursor to the
next line.
age: This is the value that replaces %d in the format string. So, the output will be:
Hello, I am 20 years old!
28
Easy2Siksha
Why is printf() So Cool?
1. Flexibility: It can display anythingnumbers, words, even calculations.
2. Customization: You can control how data looks. For example, you can show numbers
with decimals, spaces, or even align them!
3. Multi-purpose: Want to print a mix of text and numbers? No problem!
printf("I scored %d out of %d, which is %.2f%%\n", 45, 50, 90.0);
Here’s what happens:
%d prints the integer scores.
%.2f prints a number with two decimal places (90.00).
The output would be:
I scored 45 out of 50, which is 90.00%
What About putchar()?
Now, let’s talk about putchar(), the tiny bird. It’s much simplerit can only handle one
character at a time. Think of it like this: If printf() is your ship’s loud megaphone, putchar() is
like tapping out a message using single letters.
Here’s how you use putchar() in a program:
#include <stdio.h>
int main() {
putchar('H'); // Prints the letter H
putchar('i'); // Prints the letter i
putchar('\n'); // Moves to the next line
return 0;
}
Output:
Hi
But that’s not all. You can use putchar() inside a loop to make it repeat messages:
#include <stdio.h>
int main() {
for (char letter = 'A'; letter <= 'Z'; letter++) {
29
Easy2Siksha
putchar(letter); // Prints each letter from A to Z
}
putchar('\n');
return 0;
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Comparing printf() and putchar()
Feature
printf()
putchar()
Purpose
Prints strings, numbers, and complex
outputs.
Prints a single character.
Flexibility
Very flexible; can handle multiple data types
and formats.
Very limited; only one character
at a time.
Ease of
Use
Requires a bit more effort (e.g., format
specifiers like %d or %f).
Simpler; just give it a single
character.
Best For
Printing complete sentences, numbers, or
detailed outputs.
Printing characters one by one,
e.g., in loops.
Story Recap: How to Use Each Function
1. printf(): Use this when you want your magical ship to announce something biglike
sentences, numbers, or combined information. It’s the megaphone of your ship,
capable of explaining everything clearly in one go.
2. putchar(): Call the tiny bird when you need to build something letter by letter, like
spelling out a name or printing the alphabet.
Here’s a fun side-by-side program to summarize both:
#include <stdio.h>
int main() {
printf("Captain's Log: The magical ship says:\n");
printf("Hello, I am learning C programming!\n\n");
30
Easy2Siksha
printf("Now the tiny bird spells:\n");
char message[] = "Code";
for (int i = 0; message[i] != '\0'; i++) {
putchar(message[i]); // Print each letter in the word "Code"
}
putchar('\n'); // New line
return 0;
}
Output:
Captain's Log: The magical ship says:
Hello, I am learning C programming!
Now the tiny bird spells:
Why Learn Both?
Use printf() when you need your program to shout out important information in a
single go.
Use putchar() when you want to work with individual characters or create something
step by step, like a puzzle.
5. (a) Discuss the use of different forms of If-else statement using suitable example.
(b) What is the purpose of Continue statement ? Explain its use. Compare it with break
statement.
Ans: Fun Story Version: "The Adventure of the Wise Villager and the IF-ELSE Paths"
Imagine a wise old villager named IF. He stands at a crossroads where travelers often come
with dilemmas. The road splits into different paths based on their decisions. IF has magical
powers and uses his wisdom to guide each traveler to the right path. His trusty companion,
ELSE, helps handle any unexpected situations.
One day, three friendsAlice, Bob, and Charliearrive at the crossroads. Each has a unique
situation, and they must choose the right path. Let’s see how IF and ELSE help them.
Forms of IF-ELSE Statements
1. Simple IF Statement
The Scenario: Alice says, "I will only take the path if it’s sunny."
31
Easy2Siksha
The wise villager tells Alice, "Look up! If the sky is clear and sunny, take the right path."
In programming, this looks like:
if (isSunny) {
printf("Take the right path.\n");
}
Here, IF only checks one condition: Is it sunny? If true, Alice follows the sunny path. If not,
she waits.
2. IF-ELSE Statement
The Scenario: Bob says, "I’ll take the sunny path, but if it rains, I’ll take the left path."
The villager tells him:
"If it’s sunny, go right. Else, go left."
In programming:
if (isSunny) {
printf("Take the sunny path.\n");
} else {
printf("Take the rainy path.\n");
}
Here, IF checks the condition (is it sunny?). If true, Bob goes one way. If false, ELSE guides
him another way. This ensures Bob has a clear direction no matter the weather.
3. IF-ELSE IF Ladder
The Scenario: Charlie has a more complex problem. He says, "If it’s sunny, I’ll go right. If it
rains, I’ll go left. If it’s cloudy, I’ll wait here."
The villager says:
"If it’s sunny, go right.
Else if it rains, go left.
Else if it’s cloudy, stay here."
In programming:
if (isSunny) {
printf("Take the sunny path.\n");
} else if (isRaining) {
printf("Take the rainy path.\n");
} else if (isCloudy) {
32
Easy2Siksha
printf("Wait at the crossroads.\n");
}
Here, IF checks one condition at a time. If none of the conditions are true, Charlie stays put.
4. Nested IF-ELSE
The Scenario: A new traveler arrives with an even more complicated problem. "If it’s sunny,
I’ll take the right path. But if it’s sunny and windy, I’ll wait under the tree. If it rains, I’ll use
my umbrella and take the left path."
The villager scratches his head and says:
"If it’s sunny, then check if it’s windy.
If windy, wait under the tree.
Otherwise, take the right path.
Else, if it rains, use an umbrella and go left."
In programming:
if (isSunny) {
if (isWindy) {
printf("Wait under the tree.\n");
} else {
printf("Take the sunny path.\n");
}
} else if (isRaining) {
printf("Use an umbrella and take the rainy path.\n");
}
Here, IF checks nested conditions inside the sunny scenario. It allows for more specific
decisions.
5. Switch-Case Statement (A Cousin of IF-ELSE)
While not exactly IF-ELSE, this is another way to make decisions. Imagine travelers
choosing paths based on their favorite colors:
Red → Right
Blue → Left
Green → Straight
The villager uses a switch case:
33
Easy2Siksha
switch (favoriteColor) {
case 'R':
printf("Take the right path.\n");
break;
case 'B':
printf("Take the left path.\n");
break;
case 'G':
printf("Go straight.\n");
break;
default:
printf("Stay at the crossroads.\n");
}
Switch is like IF-ELSE, but it's better for comparing specific values.
Key Concepts to Remember
1. Simple IF is like a one-way gate: check one condition.
2. IF-ELSE gives two options: one for true, another for false.
3. IF-ELSE IF Ladder handles multiple conditions, one after the other.
4. Nested IF-ELSE allows deeper decisions based on combinations of conditions.
5. Switch-Case is great for checking specific values like numbers or characters.
Complete Example: Choosing a Snack at the Crossroads
Let’s say a traveler has these options:
If they’re hungry and love sweets, they choose a candy bar.
If they’re hungry and love salty snacks, they choose chips.
If they’re not hungry, they choose water.
The program:
#include <stdio.h>
int main() {
34
Easy2Siksha
int isHungry = 1; // 1 means true
char snackPreference = 'S'; // 'S' for sweet, 'T' for salty
if (isHungry) {
if (snackPreference == 'S') {
printf("Here’s a candy bar.\n");
} else if (snackPreference == 'T') {
printf("Here’s a pack of chips.\n");
}
} else {
printf("Have some water.\n");
}
return 0;
}
In Real Life
Think of IF-ELSE as how you make daily decisions:
If you’re thirsty, you drink water.
Else if you’re hungry, you eat food.
Else you take a nap.
Programming with IF-ELSE is just writing these decisions in code for computers to follow. It’s
like giving instructions to a robot!
Recap of the Story
By guiding travelers through their dilemmas, the wise villager and his companion showed us
the magic of decision-making in programming. Just like travelers at a crossroads, programs
use IF-ELSE statements to decide what to do based on conditions. Whether it’s a sunny day
or snack preferences, IF and ELSE are always ready to help.
35
Easy2Siksha
(b) The Purpose of the Continue Statement and its Use Explained in a Fun and Simple
Story!
Ans: Imagine you’re playing a treasure hunt game with your friends. Your goal is to collect as
many treasures as possible by visiting a series of checkpoints. However, at some
checkpoints, there are obstacles like thorny bushes, and you just want to skip past them
without ending the game. This is where the "continue" statement comes into play.
Now, let’s add a twist to the game. If you find a dangerous trap at a checkpoint, you want to
quit the game entirely. That’s where the "break" statement is used. Let’s dive deeper into
this story to understand both these concepts more clearly.
The Hero of Our Story: The Continue Statement
In the treasure hunt, you’ve decided to skip checkpoints with thorny bushes but still
continue playing. The continue statement in programming is like saying:
"Hey, I don’t want to deal with this specific checkpoint, so I’ll skip it and move on to the next
one."
In a computer program, the continue statement is used inside loops. It tells the program:
"Don’t execute the remaining code for this loop iteration; just jump to the next iteration."
How the Continue Statement Works
Let’s look at an example of how the continue statement works in programming.
Suppose you’re checking numbers from 1 to 10, but you want to skip the number 5 because
it’s your unlucky number. Here’s how you’d write it in C:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip this iteration if i is 5
}
printf("%d\n", i); // Print the number
}
return 0;
}
What happens here?
1. The loop starts with i = 1 and prints 1, then moves to the next iteration.
36
Easy2Siksha
2. When i = 5, the continue statement is executed, and the program skips the
printf("%d\n", i); part for i = 5.
3. The program doesn’t stop; it simply skips 5 and continues to print 6, 7, 8, 9, and 10.
The Villain of the Story: Obstacles That Break the Game
Now, imagine a dangerous trap in your treasure hunt game. If you land on this trap, the
game is over. Similarly, in programming, the break statement is used to stop the loop
entirely. It’s like saying:
"I’ve had enough; I’m quitting the game!"
Here’s an example to understand the break statement. Suppose you’re checking numbers
from 1 to 10, but you want to stop the loop completely when you reach 5.
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
printf("%d\n", i); // Print the number
}
return 0;
}
What happens here?
1. The loop starts with i = 1 and prints 1, then moves to the next iteration.
2. When i = 5, the break statement is executed, and the program stops the loop
entirely.
3. Numbers 6 to 10 are never printed because the loop is terminated.
Comparing Continue and Break Statements
Let’s compare continue and break with a simple table:
Feature
Continue Statement
Break Statement
Purpose
Skips the current iteration of the loop.
Exits the loop entirely.
37
Easy2Siksha
Feature
Continue Statement
Break Statement
Effect on the
Loop
The loop continues with the next
iteration.
The loop stops immediately.
Use Case
Used when you want to skip some
specific steps but continue looping.
Used when you want to stop the
loop when a condition is met.
Example
Skipping the number 5 in a sequence.
Stopping the loop when the number
5 is encountered.
Real-Life Analogy to Remember the Difference
Think of a school race with checkpoints.
Continue: If you see a puddle at a checkpoint, you jump over it and keep running
(skip the checkpoint but stay in the race).
Break: If you twist your ankle during the race, you stop running entirely (leave the
race).
Why Use the Continue Statement?
The continue statement is helpful when:
1. You want to avoid unnecessary steps in a loop.
2. You need to focus on specific data and ignore others without disrupting the entire
loop.
For example, in a program that filters odd numbers from 1 to 10:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i); // Print only odd numbers
}
return 0;
}
38
Easy2Siksha
Output:
1
3
5
7
9
Here, the continue statement helps us ignore even numbers and print only odd ones.
Why Use the Break Statement?
The break statement is helpful when:
1. You want to terminate the loop early based on a condition.
2. You know continuing the loop is unnecessary or would cause errors.
For example, if you’re searching for a specific number in a list:
#include <stdio.h>
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int target = 6;
for (int i = 0; i < 5; i++) {
if (numbers[i] == target) {
printf("Found %d at index %d\n", target, i);
break; // Stop searching once the target is found
}
}
return 0;
}
Output:
Found 6 at index 2
Here, the break statement helps stop the loop as soon as the number 6 is found.
39
Easy2Siksha
The Moral of the Story
Think of continue as a "skip" button and break as a "stop" button:
Use continue when you want to skip unnecessary steps and focus on the next ones.
Use break when you want to stop everything and exit the loop immediately.
6. What is Function? What are differences between passing an array to a function and
passing a single-valued data item to a function? Explain using example.
Ans: What is a Function?
In simple terms, a function is a block of code or a set of instructions that performs a specific
task in a program. Functions are used to break down large, complex problems into smaller,
manageable parts, making the code easier to read, maintain, and reuse.
Imagine a function as a machine. For instance, a washing machine is designed to wash
clothes. When you want to use it, you give it inputs (like clothes, detergent, and water), and
it performs its task (washing the clothes). Similarly, in programming, a function may take
some input, process it, and then give an output.
Key Points about Functions:
1. Reusability: Functions can be used multiple times, so you don’t have to write the
same code repeatedly.
2. Modularity: Programs become organized because functions can handle specific tasks
independently.
3. Ease of Debugging: If there is an error in a function, you only need to fix that
particular function without affecting the rest of the code.
4. Clarity: Functions make the code cleaner and easier to understand.
Types of Functions
1. Built-in Functions: These are predefined in programming languages. For example, in
C, printf() is a built-in function used to display output.
2. User-defined Functions: These are created by programmers for specific tasks. For
example, if you want to calculate the square of a number, you can write a function
for it.
Passing Data to a Function
When you use a function, you often give it some inputs, called arguments or parameters, to
work with. These inputs can be either:
40
Easy2Siksha
1. Single-valued data items (like numbers or characters).
2. Arrays (a collection of multiple related values stored together).
Let’s explore the differences between these two approaches.
Passing a Single-valued Data Item to a Function
When you pass a single-valued data item (e.g., an integer, character, or floating-point value)
to a function, only one value is sent to the function. This value can either be copied or
directly referenced, depending on how the data is passed (e.g., by value or by reference).
Let’s say we want to write a function that doubles a number:
OUTPUT:
Key Observations:
1. The function doubleNumber() takes one single-valued input, num.
2. Inside the function, num is modified (doubled), but this change does not affect the
original value in main(). This happens because the value was passed by value,
meaning the function works on a copy of the original data.
Passing an Array to a Function
When you pass an array to a function, the entire collection of values is passed. However,
instead of copying all the values, the address (or reference) of the array is sent to the
function. This means the function can directly access and modify the elements of the
original array.
41
Easy2Siksha
Example:
Let’s write a program to double the values in an array:
OUTPUT:
Key Observations:
1. The function doubleArray() accepts the array arr and its size as parameters.
2. Inside the function, the elements of the array are modified directly. This is possible
because the function receives the address of the original array, allowing it to access
and change the original data.
3. Unlike single-valued data, changes to the array inside the function are reflected back
in the main program.
42
Easy2Siksha
Key Differences Between Passing a Single-valued Data Item and an Array
Aspect
Array
Nature of Data
A collection of values is passed.
Memory Usage
The address of the array is
passed, so no copying is done.
Changes to
Original Data
Changes made inside the
function directly affect the
original array.
Parameter
Representation
Data is passed as a reference
(e.g., int arr[]).
Use Case
Suitable for operations on
multiple related values (e.g.,
processing a list).
Analogy to Understand the Difference
Think of the function as a workshop, and the data you pass to it as materials.
1. Single-valued Data Item:
o Imagine giving the workshop one item, like a shirt, to fix. They make a copy of
the shirt, work on it, and return the modified copy to you. The original shirt
remains untouched.
2. Array:
o Now, imagine giving the workshop an entire box of clothes. Instead of
copying the clothes, they work directly on the items in the box. When they
are done, you receive the same box with the modified clothes.
Advantages and Use Cases
1. Passing Single-valued Data Items:
o Useful when you need to perform calculations or operations on individual
pieces of data without altering the original value.
o Example: Calculating the square or cube of a number.
43
Easy2Siksha
2. Passing Arrays:
o Ideal for tasks that involve multiple related values, like processing a list of
exam scores or updating a list of prices.
o Example: Doubling the values in an array, sorting an array, or finding the
maximum value.
Conclusion
Understanding the difference between passing a single-valued data item and passing an
array to a function is important in programming. While single-valued data gives the function
limited scope to work with, arrays allow the function to operate on multiple related values
efficiently. By mastering these concepts, you can write better, more modular code that is
easy to understand and maintain.
7. (a) Explain the use of pointers in Call by Less Reference parameter passing for functions
using example.
(b) Write a program using pointers to swap the values of two integer numbers.
Ans: Simplified Story Version: "Pointers and the Tale of the Magical Postman"
Imagine there’s a magical postman named Pointer, who works in the kingdom of Computer
Land. This postman has a special job: instead of delivering objects directly to people, he
gives them the exact address of where the objects are stored in a magical warehouse called
Memory. By using these addresses, the people in the kingdom can quickly and easily find,
use, or even change the objects in the warehouse without moving the entire object back
and forth.
Now, let’s meet two friends in Computer Land: Call by Value and Call by Reference. They
both love solving problems for the King (your computer programs), but they go about their
jobs differently. Here’s the fun part of their story!
Call by Value: The Forgetful Friend
Call by Value is a little clumsy. Whenever he needs to deliver something (like a number or a
letter) to someone, he makes a copy of the original item and carries it.
For example:
If the King asks him to take a message (like the number 5) to a minister, he writes
down “5” on a piece of paper and hands it over.
If the minister changes the number to 10, Call by Value doesn’t care. The original
message stays 5 because he only delivered a copy.
44
Easy2Siksha
But here’s the problem: copying things over and over is slow and takes up a lot of space!
Plus, the King sometimes gets frustrated because the original doesn’t change when the
minister updates it.
Call by Reference: The Practical Problem-Solver
Call by Reference is smarter and more practical. Instead of copying the entire item, he uses
his magical postman, Pointer.
When the King gives him a task, Call by Reference doesn’t carry the whole message.
Instead, he asks Pointer to deliver the address where the message is stored in the
warehouse.
Here’s how it works:
1. The King gives Call by Reference a number, like 5, stored at an address, say 1001.
2. Pointer hands the address 1001 to the minister.
3. The minister walks to the warehouse, finds the number 5 at address 1001, and
changes it to 10 if needed.
Now, when the minister makes any changes, the original number changes because everyone
is working directly with the same address. This saves time, avoids unnecessary copying, and
makes everyone in Computer Land very happy!
How Pointers Work in Functions: A Real-Life Example
Let’s take a simple example to show how Call by Reference works with pointers in a
program:
Problem:
We want to swap two numbers using a function. For this, Call by Reference with pointers
will help us.
Code Example:
#include <stdio.h>
// Function to swap two numbers using pointers
void swap(int *x, int *y) {
int temp;
temp = *x; // Store the value at address x in temp
*x = *y; // Copy the value at address y to address x
*y = temp; // Copy temp to address y
}
45
Easy2Siksha
int main() {
int a = 5, b = 10;
printf("Before swapping: a = %d, b = %d\n", a, b);
// Call the swap function
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Explanation:
1. Pointer Basics:
o * (dereference operator): Accesses the value stored at a memory address.
o & (address operator): Gets the memory address of a variable.
2. What Happens in the Code:
o In main(), we have two variables a = 5 and b = 10.
o When we call swap(&a, &b), we pass the addresses of a and b to the swap
function.
o Inside swap, the parameters x and y are pointers that point to a and b's
addresses.
o Using *x and *y, we directly modify the values stored at the addresses of a
and b.
3. Result:
o Before swapping: a = 5, b = 10.
o After swapping: a = 10, b = 5.
o This happens because the swap function directly changes the values in
memory through their addresses.
46
Easy2Siksha
Why Use Pointers for Call by Reference?
Efficiency: Instead of copying large amounts of data, only addresses are passed,
which is faster.
Direct Access: Functions can modify the original data because they’re working with
the actual memory address.
Memory Management: Helps in managing dynamic memory allocation.
The Moral of the Story
Pointers are like magical postmen who save the day by delivering exact addresses instead of
bulky objects. By using Call by Reference with pointers, functions in programming can
efficiently modify the original data, making programs faster and more memory-efficient. So,
the next time you write a program, remember the tale of the magical postman, Pointer!
(b) A Fun Story about Swapping Two Numbers
Ans: Imagine you have two magical boxes, Box A and Box B, and they contain candies. Box A
has 5 candies, and Box B has 10 candies. Your friend wants to swap the candies between the
boxes without spilling anything. But there's a twist! You have a magic wand (a pointer in
programming) that can help you exchange the candies easily. Let’s learn how to do this
using C++ programming.
Breaking It Down: What Are Pointers?
Before jumping into the swapping part, let’s understand the magic wand pointers.
In C++:
1. Pointers are variables that store the address of another variable. Think of them as
treasure maps pointing to the exact location of something in memory.
2. Instead of holding values like normal variables, they hold the address where the
value is stored.
The Idea Behind Swapping
To swap the candies in Box A and Box B:
1. Take the candy out of Box A and keep it in a temporary invisible box (like a storage
place).
2. Move the candy from Box B to Box A.
3. Finally, move the candy from the temporary box to Box B.
This way, the candies are swapped! In the programming world, this process uses pointers
for efficient swapping.
47
Easy2Siksha
The Program Code for Swapping
Here’s the C++ code that uses pointers to swap two numbers:
#include <iostream>
using namespace std;
// Function to swap two numbers using pointers
void swap(int* x, int* y) {
int temp; // Temporary storage
temp = *x; // Store the value of x in temp
*x = *y; // Assign the value of y to x
*y = temp; // Assign the value of temp to y
}
int main() {
int a, b;
// Input two numbers
cout << "Enter the first number (Box A): ";
cin >> a;
cout << "Enter the second number (Box B): ";
cin >> b;
cout << "\nBefore swapping:" << endl;
cout << "Box A = " << a << ", Box B = " << b << endl;
// Call the swap function and pass the addresses of a and b
swap(&a, &b);
cout << "\nAfter swapping:" << endl;
48
Easy2Siksha
cout << "Box A = " << a << ", Box B = " << b << endl;
return 0;
}
Step-by-Step Explanation of the Code
1. Function Definition: The Swap Spell
void swap(int* x, int* y)
This function takes two pointers as arguments (int* x and int* y).
*x and *y represent the values stored at the memory addresses passed into the
function.
2. Temporary Storage
int temp;
temp = *x;
temp is a temporary variable to hold the value of *x (Box A’s candies).
Imagine temp as a secret box to keep Box A’s candies safe during the swap.
3. Swapping the Values
*x = *y;
*y = temp;
Assign the value of *y (Box B’s candies) to *x (Box A).
Then, assign the stored value in temp (original Box A candies) to *y (Box B).
4. Using the Function
swap(&a, &b);
We pass the addresses of a and b into the function using the & operator.
Inside the function, the values of a and b are swapped using pointers.
Input and Output
Example Input:
Enter the first number (Box A): 5
Enter the second number (Box B): 10
49
Easy2Siksha
Example Output:
Before swapping:
Box A = 5, Box B = 10
After swapping:
Box A = 10, Box B = 5
Why Use Pointers?
Pointers make swapping more efficient because:
1. Memory Efficiency: They directly manipulate the memory addresses of variables
without creating unnecessary copies.
2. Reusability: The swap function can be reused for any pair of integers.
3. Versatility: Pointers are essential in advanced programming, such as dynamic
memory allocation and handling data structures.
Fun Tip: Think of Memory as a Candy Store!
1. Each candy box (variable) has a specific location (address).
2. Pointers are like maps that help you find and change what’s inside the boxes without
opening them manually.
3. Swapping with pointers is like using a magical swap spell to exchange candies
between the boxes instantly.
A Practice Challenge
Write a program to swap the values of three numbers using pointers. Think of it as swapping
candies between three magical boxes! Try to use the same logic as in this story.\
Summary: Key Points to Remember
1. Pointers store memory addresses, not values.
2. Swapping with pointers involves:
o Using temporary storage.
o Directly manipulating the values stored at the memory addresses.
3. Pointers make programs more efficient and flexible.
50
Easy2Siksha
8. (a) What is Structure? How it is different from an array? How can a structure member
be accessed? Explain using suitable example.
(b) Explain the concept of Union. In what way does the initialization of a union variable
differ from the initialization of a structure variable?
Ans: The Story of Arrays and Structures
Once upon a time in the world of programming, there were two friends, Array and Structure. They
both loved helping programmers organize and manage data, but they had very different
personalities and ways of working. Let's dive into their story and understand how they are different,
and how Structure works!
Meet Array: The Organized Family
Array was like a big family where everyone looked the same and lived in the same neighborhood.
Imagine a row of houses, and each house in this row had people (data) of the same profession (data
type). For example:
If it's a row of teachers, every house has a teacher.
If it's a row of doctors, every house has a doctor.
In programming terms:
An array can only hold data of the same type.
For instance, if you create an array of integers, all its elements must be integers.
Here's an example of an array:
int numbers[5] = {10, 20, 30, 40, 50};
Here, the "neighborhood" has five houses, each holding an integer value.
Meet Structure: The Multitalented Team
Structure, on the other hand, was like a team of superheroes where each member had a unique
superpower. This team could have a doctor, a teacher, a firefighter, and a scientistall working
together under one team name. Unlike the array family, Structure allowed diversity.
In programming terms:
A structure can group together different types of data into a single unit.
Each piece of data in the structure is called a member.
Here’s an example of a structure:
struct Person {
char name[50];
int age;
float height;
};
51
Easy2Siksha
Here, the "team" is called Person, and it has three members:
name (a string of characters),
age (an integer),
height (a floating-point number).
Key Differences Between Array and Structure
Feature
Array
Structure
Data
Type
All elements must be of the same type.
Members can be of different types.
Purpose
Used for handling collections of similar
data.
Used for grouping related but different data.
Access
Accessed using an index (e.g., array[0]).
Accessed using a dot operator (e.g.,
struct.member).
Memory
All elements are stored in contiguous
memory.
Members may have different memory
alignments.
Accessing Structure Members
To access a structure’s members, you need to use the dot operator (.). Think of it as asking a specific
superhero about their skill.
Example:
Let’s create and use the Person structure:
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Creating a structure variable
52
Easy2Siksha
struct Person p1;
// Assigning values to members
strcpy(p1.name, "Alice");
p1.age = 25;
p1.height = 5.4;
// Accessing and printing the values
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Height: %.1f\n", p1.height);
return 0;
}
Output:
Name: Alice
Age: 25
Height: 5.4
Here’s what happens:
1. We create a superhero (Person) named p1.
2. Using the dot operator (p1.name, p1.age, p1.height), we assign and retrieve data from the
structure.
Fun Scenario: Comparing Array and Structure
Imagine you’re organizing data for your school:
1. Array: You have 30 students in a class, and you only need to record their marks. An array is
perfect because all the data (marks) are of the same type (numbers).
int marks[30];
Each student’s marks are stored in consecutive slots, like marks[0], marks[1], and so on.
2. Structure: Now, you want to record detailed information about each student, like their
name, age, and marks. Here’s where a structure shines:
53
Easy2Siksha
struct Student {
char name[50];
int age;
int marks;
};
struct Student s1;
You can store all the data about one student (s1) in one place, with each piece of data being
different.
Structure: A Team for Real-Life Problems
Structures are extremely useful in real-life programming scenarios, like:
1. Student Database:
struct Student {
char name[50];
int rollNo;
float percentage;
};
2. Employee Records:
c
struct Employee {
char name[50];
int id;
float salary;
};
3. Game Characters:
c
struct Character {
char name[50];
int health;
int attackPower;
};
54
Easy2Siksha
Conclusion: Arrays and Structures Together
Sometimes, you might need both Arrays and Structures to solve a problem. For example, if you want
to store data about multiple students:
struct Student {
char name[50];
int rollNo;
float percentage;
};
struct Student students[30]; // An array of structures
Now you can organize data for 30 students, each with their name, roll number, and percentage.
Moral of the Story
Arrays and Structures are both powerful tools in the C language. While arrays are perfect for storing
large amounts of similar data, structures are ideal for bundling together different types of data into
a cohesive unit. By using the right tool for the job, you can become a superhero programmer, just
like our friends in this story!
Note: This Answer Paper is totally Solved by Ai (Artificial Intelligence) So if You find Any Error Or Mistake . Give us a
Feedback related Error , We will Definitely Try To solve this Problem Or Error.